<template>
  <el-dialog
    :title="!dataForm.userId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    :visible.sync="visible"
    :fullscreen="true">
    <el-tabs v-model="activeName">
      <el-tab-pane label="通用信息" name="first">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
          <el-form-item label="商铺名" prop="shopname">
            <el-input v-model="dataForm.shopname" placeholder="商铺名" maxlength="30" clearable></el-input>
          </el-form-item>
          <el-form-item label="所属部门" prop="deptId">
            <el-cascader
              placeholder="所属部门"
              :options="deptTree"
              :props="deptTreeProps"
              v-model="dataForm.deptId"
              filterable
              change-on-select
              clearable
              style="width:100%;"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="所属用户" prop="userId">
            <el-select
              clearable
              v-model="dataForm.userId"
              filterable
              remote
              :remote-method="searchShopUser"
              :loading="remoteLoading"
              placeholder="请输入关键词(真实姓名/昵称/用户名/电话号码/身份证号/邮箱)"
              style="width: 100%;">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.realname+'|'+item.nickname+'|'+item.username+'，'+item.mobile+'，'+item.idcard+'，'+item.email"
                :value="item.userId">
                <el-row :gutter="10">
                  <el-col :span="4" class="userInfo">{{item.realname}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.nickname}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.username}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.mobile}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.idcard}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.email}}</el-col>
                </el-row>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推荐人" prop="referrer">
            <el-select
              clearable
              v-model="dataForm.referrer"
              filterable
              remote
              :remote-method="searchShopUser"
              :loading="remoteLoading"
              placeholder="请输入关键词(真实姓名/昵称/用户名/电话号码/身份证号/邮箱)"
              style="width: 100%;">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.realname+'|'+item.nickname+'|'+item.username+'，'+item.mobile+'，'+item.idcard+'，'+item.email"
                :value="item.userId">
                <el-row :gutter="10">
                  <el-col :span="4" class="userInfo">{{item.realname}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.nickname}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.username}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.mobile}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.idcard}}</el-col>
                  <el-col :span="4" class="userInfo">{{item.email}}</el-col>
                </el-row>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域" prop="area">
            <area-cascader type='text' v-model="dataForm.area" :level='1' :data="pcaa" placeholder="请选择区域"></area-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="addr">
            <el-input v-model="dataForm.addr" placeholder="请输入详细地址" maxlength="50" clearable></el-input>
          </el-form-item>
          <el-form-item label="简介" prop="simpleDesc">
            <el-input type="textarea" :rows="4" v-model="dataForm.simpleDesc" placeholder="商铺简介(限200字)" maxlength="200" clearable></el-input>
          </el-form-item>
          <el-form-item label="到期时间" prop="expirationTime">
            <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.expirationTime" style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="状态" size="mini" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="列表图" prop="listPicUrl">
                <el-row>
                  <el-col :span="12">
                    <el-upload
                      class="avatar-uploader"
                      :action="updateUrl"
                      :show-file-list="false"
                      :on-success="handleListPicUrlSuccess"
                      :before-upload="beforeListPicUrlUpload">
                      <img v-if="dataForm.listPicUrl" :src="dataForm.listPicUrl" class="pic-url"/>
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-col>
                  <el-col :span="12">
                    <el-button type="primary" plain>预览列表图</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片" prop="picUrl">
                <el-row>
                  <el-col :span="12">
                    <el-upload
                      class="avatar-uploader"
                      :action="updateUrl"
                      :show-file-list="false"
                      :on-success="handlePicUrlSuccess"
                      :before-upload="beforePicUrlUpload">
                      <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="pic-url"/>
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-col>
                  <el-col :span="12">
                    <el-button type="primary" plain>预览图片</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="详细描述" name="second">
        <tinymce-editor id="shopDesc" :url="updateUrl" ref="tinymce" :uploadImg="uploadImg" :value="dataForm.shopDesc" @input="getContent"></tinymce-editor>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { pcaa } from 'area-data'
  import { treeDataTranslate, getTreeId } from '@/utils'
  import TinymceEditor from '@/components/tinymce-editor'
  export default {
    data () {
      var validateeferrer = (rule, value, callback) => {
        if (/\S/.test(this.dataForm.userId) && (this.dataForm.userId === value)) {
          callback(new Error('推荐人与所属用户不能为同一个人'))
        } else {
          callback()
        }
      }
      return {
        // 对话框是否显示
        visible: false,
        // 列表框远程加载
        remoteLoading: false,
        // tab标签默认显示的标签页
        activeName: 'first',
        dataForm: {
          id: 0,
          deptId: [],
          userId: '',
          referrer: '',
          shopname: '',
          area: '',
          addr: '',
          listPicUrl: '',
          picUrl: '',
          simpleDesc: '',
          shopDesc: '',
          status: '',
          createTime: '',
          expirationTime: ''
        },
        dataRule: {
          shopname: [
            { required: true, message: '商铺名不能为空', trigger: 'blur' }
          ],
          deptId: [
            { required: true, message: '所属部门不能为空', trigger: 'blur' }
          ],
          userId: [
            { required: true, message: '所属用户不能为空', trigger: 'blur' }
          ],
          referrer: [
            { validator: validateeferrer, trigger: 'blur' }
          ],
          area: [
            { required: true, message: '区域不能为空', trigger: 'blur' }
          ],
          addr: [
            { required: true, message: '地址不能为空', trigger: 'blur' }
          ],
          listPicUrl: [
            { required: true, message: '列表图片不能为空', trigger: 'blur' }
          ],
          simpleDesc: [
            { required: true, message: '简介不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '状态不能为空', trigger: 'blur' }
          ]
        },
        // 通过搜索远程加载的用户
        userList: [],
        // 部门树形数据
        deptTree: [],
        // 部门列表数据
        deptList: [],
        // 联级选择加载项
        deptTreeProps: {
          value: 'deptId',
          label: 'name',
          children: 'children'
        },
        // 图片上传路径
        updateUrl: '',
        // 富文本编辑中的图片路径
        uploadImg: []
      }
    },
    components: {
      TinymceEditor
    },
    computed: {
      pcaa: function () {
        return pcaa
      }
    },
    methods: {
      // 同步得到富文本的值
      getContent (content) {
        this.dataForm.shopDesc = content
      },
      // 初始化
      init (id) {
        this.updateUrl = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/dept/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.deptList = data.deptList
          this.deptTree = treeDataTranslate(data.deptList, 'deptId')
        }).then(() => {
          this.visible = true
          this.uploadImg = []
          this.userList = []
          if (this.$refs.tinymce) {
            this.$refs.tinymce.setContent('')
          }
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/back/shop/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.shopname = data.shop.shopname
                this.dataForm.userId = data.shop.userId
                this.dataForm.referrer = data.shop.referrer
                this.dataForm.addr = data.shop.addr
                this.dataForm.listPicUrl = data.shop.listPicUrl
                this.dataForm.picUrl = data.shop.picUrl
                this.dataForm.simpleDesc = data.shop.simpleDesc
                this.dataForm.status = data.shop.status
                this.dataForm.createTime = data.shop.createTime
                this.dataForm.expirationTime = data.shop.expirationTime
                this.dataForm.deptId = getTreeId(this.deptList, data.shop.deptId, 'deptId')
                this.dataForm.area = data.shop.area ? data.shop.area.split(',') : ''
                this.dataForm.shopDesc = data.shop.shopDesc ? data.shop.shopDesc : ''
                if (this.$refs.tinymce && data.shop.shopDesc) {
                  this.$refs.tinymce.setContent(data.shop.shopDesc)
                }
                if (data.shop.user) {
                  this.userList.unshift(data.shop.user)
                }
                if (data.shop.referr && (!data.shop.user || data.shop.referr.userId !== data.shop.user.userId)) {
                  this.userList.unshift(data.shop.referr)
                }
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/back/shop/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'deptId': this.dataForm.deptId[this.dataForm.deptId.length - 1],
                'userId': this.dataForm.userId,
                'referrer': this.dataForm.referrer,
                'shopname': this.dataForm.shopname,
                'area': this.dataForm.area.toString(),
                'addr': this.dataForm.addr,
                'listPicUrl': this.dataForm.listPicUrl,
                'picUrl': this.dataForm.picUrl,
                'simpleDesc': this.dataForm.simpleDesc,
                'shopDesc': this.dataForm.shopDesc,
                'status': this.dataForm.status,
                'expirationTime': this.dataForm.expirationTime ? new Date(this.dataForm.expirationTime).getTime() : undefined
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                if (this.uploadImg && this.uploadImg.length > 0) {
                  for (let url in this.uploadImg) {
                    if (this.dataForm.shopDesc.indexOf(url) === -1) {
                      this.deletePic(this.uploadImg[url])
                    }
                  }
                }
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 远程搜索商城用户
      searchShopUser (keyword) {
        if (keyword !== '') {
          this.$http({
            url: this.$http.adornUrl(`/back/shopUser/search/${keyword}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.userList = data.shopUsers
            } else {
              this.userList = []
            }
          })
        } else {
          this.userList = []
        }
      },
      // 上传列表图片之前的钩子
      beforeListPicUrlUpload (file) {
        var fileType = ['image/jpeg', 'image/png', 'image/jpg']
        const isPic = fileType.join(',').indexOf(file.type) !== -1
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isPic) {
          this.$message.error('不支持此格式的图片!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        if (isPic && isLt2M && this.dataForm.listPicUrl) {
          this.deletePic(this.dataForm.listPicUrl)
        }
        return isPic && isLt2M
      },
      // 列表图片上传成功时的钩子
      handleListPicUrlSuccess (response) {
        if (response && response.code === 0) {
          this.dataForm.listPicUrl = response.url
          this.updatefile()
        } else {
          this.$message.error(response.msg)
        }
      },
      // 上传图片之前的钩子
      beforePicUrlUpload (file) {
        var fileType = ['image/jpeg', 'image/png', 'image/jpg']
        const isPic = fileType.join(',').indexOf(file.type) !== -1
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isPic) {
          this.$message.error('不支持此格式的图片!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        if (isPic && isLt2M && this.dataForm.picUrl) {
          this.deletePic(this.dataForm.picUrl)
        }
        return isPic && isLt2M
      },
      // 图片上传成功时的钩子
      handlePicUrlSuccess (response) {
        if (response && response.code === 0) {
          this.dataForm.picUrl = response.url
          this.updatefile()
        } else {
          this.$message.error(response.msg)
        }
      },
      // 通过url删除图片
      deletePic (url) {
        if (url) {
          this.$http({
            url: this.$http.adornUrl('/sys/oss/deleteByUrl'),
            method: 'post',
            params: this.$http.adornParams({'url': url})
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message.success('旧文件删除成功')
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      },
      // 取消操作
      cancel () {
        var that = this
        if (!that.dataForm.id) {
          if (that.dataForm.listPicUrl) { that.deletePic(that.dataForm.listPicUrl) }
          if (that.dataForm.picUrl) { that.deletePic(that.dataForm.picUrl) }
        }
        if (that.uploadImg && that.uploadImg.length > 0) {
          for (let url in that.uploadImg) {
            that.deletePic(that.uploadImg[url])
          }
        }
        that.visible = false
      },
      // 更新富文件操作
      updatefile () {
        var that = this
        if (that.dataForm.id) {
          that.$http({
            url: that.$http.adornUrl(`/back/shop/update`),
            method: 'post',
            data: that.$http.adornData({
              'id': that.dataForm.id,
              'listPicUrl': that.dataForm.listPicUrl,
              'picUrl': that.dataForm.picUrl
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              that.$message.success('文件更改成功')
            } else {
              that.$message.error(data.msg)
            }
          })
        }
      }
    }
  }
</script>

<style>
  .area-select.large {
    width:100%;
  }
  .area-select{
    height: 36px;
  }
  .area-select .area-selected-trigger{
    padding: 0px 15px;
  }
  .userInfo{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .el-form-item.is-error .area-select{
    border-color: #f56c6c;
  }
  .el-form-item.is-success .area-select{
    border-color: #67c23a;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .pic-url {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
